package cn.it.ws.b;

import java.io.FileInputStream;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;

/*
 * 调用第三方WS服务,让项目有手机号查询的功能
 * 
 * HttpClient:测试工具, 可以在Java代码中模拟HTTP请求协议
 * */
public class PhoneClient {

	public void get(String number) throws Exception {
		// 创建浏览器对象
		HttpClient client = new HttpClient();
		// 填写数据,发送get或者post请求
		GetMethod get = new GetMethod(
				"http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx"
						+ "/getMobileCodeInfo?mobileCode=" + number
						+ "&userID=");
		get.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
		// 发送请求
		int code = client.executeMethod(get);
		System.out.println("http:状态码为:" + code);
		String result = get.getResponseBodyAsString();
		System.out.println("返回的结果为:" + result);
	}

	public void post(String number) throws Exception {
		// 创建浏览器对象
		HttpClient client = new HttpClient();
		// 填写数据,发送get或者post请求
		PostMethod post = new PostMethod(
				"http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo");
		// 指定传输的格式xml格式
		post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		post.setParameter("mobileCode", number);
		post.setParameter("userID", "");
		// 发送请求
		int code = client.executeMethod(post);
		System.out.println("http:状态码为:" + code);
		String result = post.getResponseBodyAsString();
		System.out.println("返回的结果为:" + result);
	}

	// 也是通过HTTP Post传输,但是传输的数据为XML格式, 有利于数据的维护
	public void soap(String number) throws Exception {
		// 创建浏览器对象
		HttpClient client = new HttpClient();
		// 填写数据,发送get或者post请求
		PostMethod post = new PostMethod(
				"http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx");
		// 指定传输的格式xml格式
		post.setRequestHeader("Content-Type", "text/xml;charset=utf-8");
		// 传输XML数据,通过流的方式加载C盘的XML数据
		post.setRequestBody(new FileInputStream("c:/soap.txt"));
		// 发送请求
		int code = client.executeMethod(post);
		System.out.println("http:状态码为:" + code);
		String result = post.getResponseBodyAsString();
		// 如果采用的是soap则返回的数据也是基于xml的soap格式
		System.out.println("返回的结果为:" + result);
	}

	public static void main(String[] args) throws Exception {
		PhoneClient client = new PhoneClient();
		client.get("18312345678");
		client.post("18312345678");
		client.soap("18312345678");
	}
}
